package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.RongYiDaiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.ec.v2.utlis.Md5Util;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * ec系统
 */
@Service
public class EcApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();



        long timeStamp = System.currentTimeMillis();


        String appId = pushApiKeyParam.getApiKey();
        String appSecret = pushApiKeyParam.getApiSecret();
        String sign = getSign(timeStamp, appId, appSecret);


        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        headMap.put("X-Ec-Cid", pushApiKeyParam.getApiCode());
        headMap.put("X-Ec-Sign", sign);
        headMap.put("X-Ec-TimeStamp", String.valueOf(timeStamp));


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("typeId", 9);
        paramMap.put("type", 1);
        paramMap.put("value", memberSourceInfo.getMobileMd5());




        log.info("【ec系统】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createGet(queryUrl)
                .header("Content-Type", "application/json")
                .headerMap(headMap, true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【ec系统】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        log.info("撞库结果resultObject : {}", resultObject);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200") ) {
            JSONObject data = resultObject.getJSONObject("data");
            Boolean isRepeat = data.getBoolean("isRepeat");
            pushApiResult.setCode(code + "|"+isRepeat);
            if(!isRepeat){
                pushApiResult.setPushSuccess(true);
            }
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("source",pushApiKeyParam.getPubKey());
        paramMap.put("userId", pushApiKeyParam.getPriKey());
        paramMap.put("company", "");
        paramMap.put("industryId", "");
        paramMap.put("country", 100000);
        paramMap.put("province", memberSourceInfo.getProvinceCode());
        paramMap.put("city", memberSourceInfo.getCityCode());
        paramMap.put("region", "");
        paramMap.put("qq", "");
        paramMap.put("email", "");
        paramMap.put("wx", "");
        paramMap.put("remark", this.getUserInfo(memberSourceInfo));
        paramMap.put("job", BaseTypeInfoEnum.Gongzuo.getNameByValue(memberSourceInfo.getGongzuo()));



        long timeStamp = System.currentTimeMillis();


        String appId = pushApiKeyParam.getApiKey();
        String appSecret = pushApiKeyParam.getApiSecret();
        String sign = getSign(timeStamp, appId, appSecret);


        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        headMap.put("X-Ec-Cid", pushApiKeyParam.getApiCode());
        headMap.put("X-Ec-Sign", sign);
        headMap.put("X-Ec-TimeStamp", String.valueOf(timeStamp));

        log.info("【ec系统】导单开始【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .headerMap(headMap, true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【ec系统】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static String getSign(long timeStamp, String appId, String appSecret){
        StringBuffer buffer = new StringBuffer();
        buffer.append("appId="+appId);
        buffer.append("&appSecret="+appSecret);
        buffer.append("&timeStamp="+timeStamp);
        return Md5Util.encryptMd5(buffer.toString()).toUpperCase();
    }

    private String getUserInfo(MemberSourceInfo memberSourceInfo){
        String sex = ObjectUtil.equals(memberSourceInfo.getSex(), 1)?"男":"女";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append("城市：" + memberSourceInfo.getCity()).append("；")
                .append("年龄：" + memberSourceInfo.getAge()).append("；")
                .append("性别：" + sex).append("；")
                .append("房产：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getHouse()).getName()).append("；")
                .append("车产：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getCar()).getName()).append("；")
                .append("公积金：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getGjj()).getName()).append("；")
                .append("逾期情况：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getYuqi()).getName()).append("；")
                .append("社保：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getShebao()).getName()).append("；")
                .append("保险：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getBaoxian()).getName()).append("；")
                .append("芝麻分：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getZhima()).getName()).append("；")
                .append("白条：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getBaitiao()).getName()).append("；")
                .append("花呗：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getHuabei()).getName()).append("；")
                .append("职业：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getGongzuo()).getName()).append("；")
        ;
        return stringBuilder.toString();
    }


    public static void main(String[] args) {
        long timeStamp = System.currentTimeMillis();


        String appId = "1180093047170400256";
        String appSecret = "Sbp9pMZozMwUM3UkpVz";
        String sign = getSign(timeStamp, appId, appSecret);

        String requestUrl="https://open.workec.com/v2/customer/getChannelSource";


        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        headMap.put("X-Ec-Cid", "20739375");
        headMap.put("X-Ec-Sign", sign);
        headMap.put("X-Ec-TimeStamp", String.valueOf(timeStamp));



        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("corpId", "20739375");
        paramMap.put("appId", appId);
        paramMap.put("secret", appSecret);


        String result = HttpUtil.createGet(requestUrl)
                .headerMap(headMap, true)
                .form(paramMap)
                .execute().body();
        System.out.println(result);
    }
}

